package cn.wolfcode.behavior.web;

import cn.wolfcode.behavior.utils.GetRandomIp;
import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class BaseController {

    @Autowired
    private StringRedisTemplate template;

    @Value("${logPath}")
    private String logPath;

    //1 随机生成设备id 100万个设备id
    @PostConstruct
    public String createDevice() throws Exception {
        int count = 100000;
        for (int i = 0; i < count; i++) {
            String deviceId = UUID.randomUUID().toString().replaceAll("-", "");
            template.opsForSet().add("device", deviceId);
        }
        return "ok";
    }

    //2 批量生成日志
    @GetMapping("create/log")
    public String createLog(String date, Integer count) throws Exception{
        FileWriter fw = new FileWriter(logPath+"/behavior" + date + ".log");
        BufferedWriter bw = new BufferedWriter(fw);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date now = sdf.parse(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        for (int i = 0; i < count; i++) {
            int hour = (int) (Math.random() * 15) + 8;
            int minute = (int) (Math.random() * 60) + 1;
            int sec = (int) (Math.random() * 60) + 1;
            calendar.set(Calendar.HOUR_OF_DAY, hour);
            calendar.set(Calendar.MINUTE, minute);
            calendar.set(Calendar.SECOND, sec);
            // 模拟日志数据生成
            Map<String, Object> map = new HashMap();
            map.put("time", calendar.getTimeInMillis()); // 毫秒数
            // 上网设备
            String device = template.opsForSet().randomMember("device");
            map.put("device",device);
            //上网方式
            String type = template.opsForSet().randomMember("type");
            map.put("type",type);
            // 上网的IP地址
            String client_ip = GetRandomIp.getRandomIp();
            map.put("client_ip",client_ip);
            // 访问的地址
            String url = template.opsForSet().randomMember("urls");
            map.put("url",url);
            // 上网的设备类型
            String device_type = template.opsForSet().randomMember("device_type");
            map.put("device_type",device_type);
            String data_str = JSON.toJSONString(map);
            bw.write(data_str);
            bw.newLine();
        }
        bw.close();
        return "ok";
    }

}